package com.yoyosys.common.util;

import cn.hutool.core.lang.SimpleCache;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * 反射工具类 
 * @author Meron
 */
@Slf4j
public class ReflectionUtils {
    /**
     * 字段缓存
     */
    private static final SimpleCache<Class<?>, List<Field>> FIELDS_CACHE = new SimpleCache<>();
    /**
     * 方法缓存
     */
    private static final SimpleCache<Class<?>, List<Method>> METHODS_CACHE = new SimpleCache<>();

    /**
    *
    * @param <T>
    * @param instance
    * @return
    */
   @SuppressWarnings("unchecked")
   public static <T> T newInstance(Class<T> clazz) {
       T newIns = (T) BeanUtils.instantiateClass(clazz);
       return newIns;
   }
    

    /**
     * 类似Class.getSimpleName()，但是可以忽略它是一个javassist生成的动态类
     *
     * @see Class#getSimpleName()
     */
    public static String getSimpleName(Class<?> clazz) {
        if (clazz == null) {
            return null;
        }
        return StrUtil.subBefore(clazz.getSimpleName(), "_$$_", false);
    }

    /**
     * 类似Class.getName()，但是可以忽略它是一个javassist生成的动态类
     *
     * @see Class#getName()
     */
    public static String getName(Class<?> clazz) {
        if (clazz == null) {
            return null;
        }
        return StrUtil.subBefore(clazz.getName(), "_$$_", false);
    }
    /**
     * 获取字段的类型
     * @return 出错返回null， 否则返回类型名称，如"java.lang.String"
     */
    public static String getFieldType(final Class<?> clazz, final String fieldName) {
    	try {
			Field field = clazz.getDeclaredField(fieldName);
			String type = field.getType().getName();		
			return type;
		} catch (Exception e) {}
    	return null;
    }
    /**
     * 获取字段的类型
     * @return 出错返回null， 否则返回类型名称，如"java.lang.String"
     */
    public static String getFieldType(final Field field) {
    	try {
			String type = field.getType().getName();		
			return type;
		} catch (Exception e) {}
    	return null;
    }

    /**
     * 循环向上转型,获取对象的DeclaredMethod.
     */
    public static Method getDeclaredMethod(final Object object, final String methodName) {
        Assert.notNull(object, "object不能为空");
        Assert.hasText(methodName, "methodName");
        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                return superClass.getDeclaredMethod(methodName);
            } catch (NoSuchMethodException e) {
                // Method不在当前类定义,继续向上转型
            }
        }
        return null;
    }
    
    /**
     * 循环向上转型,获取对象的DeclaredField.
     */
    public static Field getDeclaredField(final Object object, final String fieldName) {
        Assert.notNull(object, "object不能为空");
        Assert.hasText(fieldName, "fieldName");
        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                return superClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                // Field不在当前类定义,继续向上转型
            }
        }
        return null;
    }

    /**
     * 获取所有字段，包括从祖先继承的过来的字段。如有同名字段，则使用子类中的字段
     */
    public static List<Field> getDeclaredFields(final Object object) {
        Assert.notNull(object, "object不能为空");
        return getDeclaredFields(object.getClass());
    }

    /**
     * 获取所有字段，包括从祖先继承的过来的字段。如有同名字段，则使用子类中的字段
     */
    public static List<Field> getDeclaredFields(Class<?> clazz) {
        Assert.notNull(clazz, "clazz不能为空");
        return FIELDS_CACHE.get(clazz, () -> {
            List<Field> fields=new ArrayList<>();
            for (Class<?> superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
                Field[] f = superClass.getDeclaredFields();
                fields.addAll(Arrays.asList(f));
            }
            //过滤重复字段名称
            Set<String> fieldNames = new HashSet<>();
            List<Field> finalFields = new ArrayList<>();
            for(Field field : fields){
                String fieldName = field.getName();
                if(!fieldNames.contains(fieldName)){
                    finalFields.add(field);
                    fieldNames.add(fieldName);
                }
            }

            return finalFields;
        });
    }

 	/**
	 * Make the given field accessible, explicitly setting it accessible if
	 * necessary. The {@code setAccessible(true)} method is only called
	 * when actually necessary, to avoid unnecessary conflicts with a JVM
	 * SecurityManager (if active).
	 * @param field the field to make accessible
	 * @see Field#setAccessible
	 */
	public static void makeAccessible(Field field) {
		if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
				Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
			field.setAccessible(true);
		}
	}
	/**
	 * 查看字段是否具有指定注解
	 * @param field
	 * @param annotationClass
	 * @return
	 */
	public static boolean hasAnnotation(Field field, Class<? extends Annotation> annotationClass){
		return field.isAnnotationPresent(annotationClass);
	}
	/**
	 * 查看类是否具有指定注解
	 * @param field
	 * @param annotationClass
	 * @return
	 */
	public static boolean hasAnnotation(Class<?> clazz, Class<? extends Annotation> annotationClass){
		return clazz.isAnnotationPresent(annotationClass);
	}

    //----------------------------------
    /**
	 * 对象拷贝
	 * @param from
	 * @param to
	 * @param fromProperties
	 */
	public static void copy(Object from,  Object to, String fromProperties){
		copy(from, to, fromProperties, fromProperties);
	}
	/**
	 * 对象拷贝
	 * @param from
	 * @param to
	 * @param fromProperties 来源对象的属性
	 * @param toProperties
	 */
	public static void copy(Object from,  Object to, String fromProperties, String toProperties){
		if(from == null){
			return;
		}
		if(to == null){
			return;
		}
		if(StrUtil.isBlank(fromProperties)){
			return;
		}
		if(StrUtil.isBlank(toProperties)){
			toProperties = fromProperties;
		}
		String [] fromProps = fromProperties.split(",");
		String [] toProps = toProperties.split(",");
		int len = Math.min(fromProps.length, toProps.length);
		for(int i=0; i<len; i++){
			String fromProp = fromProps[i];
			String toProp = toProps[i];
			if(StrUtil.isBlank(fromProp) || StrUtil.isBlank(toProp)){
				continue;
			}
			fromProp = fromProp.trim();
			toProp = toProp.trim();

			try{
				Object value = null;
				if(from instanceof Map){
					value = ((Map)from).get(fromProp);
				} else {
					value = getFieldValue(from, fromProp);
				}
				setFieldValue(to, toProp, value);
			}catch(Exception e){
				continue;
			}
		}
	}
	/**
	 * Map拷贝
	 * @param from
	 * @param to
	 * @param fromKeys 源Map中要拷贝的键,逗号分割
	 */
	public static Map<String, Object> copyMap(Map<String, Object> from,  Map<String, Object> to, String fromKeys){
		return copyMap(from, to, fromKeys, fromKeys);
	}
	/**
	 * Map拷贝
	 * @param from
	 * @param to
	 * @param fromKeys 	源Map中要拷贝的键,逗号分割
	 * @param toKeys	目标Map中要设置的键,逗号分割
	 */
	public static Map<String, Object> copyMap(Map<String, Object> from,  Map<String, Object> to, String fromKeys, String toKeys){
		if(to == null){
			to = new HashMap<String, Object>();
		}
		if(from == null){
			return to;
		}
		if(StrUtil.isBlank(fromKeys)){
			return to;
		}
		if(StrUtil.isBlank(toKeys)){
			toKeys = fromKeys;
		}
		String [] fromKeyArr = fromKeys.split(",");
		String [] toKeyArr = toKeys.split(",");
		int len = Math.min(fromKeyArr.length, toKeyArr.length);
		for(int i=0; i<len; i++){
			String fromKey = fromKeyArr[i];
			String toKey = toKeyArr[i];
			if(StrUtil.isBlank(fromKey) || StrUtil.isBlank(toKey)){
				continue;
			}
			fromKey = fromKey.trim();
			toKey = toKey.trim();
			to.put(toKey, from.get(fromKey));
		}
		return to;
	}


    /**
     * 直接设置对象属性值,无视private/protected修饰符,不经过setter函数.
     */
    public static <T> void setFieldValueDirectly(final T object, final Field field, final Object value) {
        if (field == null) {
            return;
        }

        makeAccessible(field);

        try {
            field.set(object, value);
        } catch (IllegalAccessException e) {
        }
    }

    /**
     * 直接设置对象属性值,无视private/protected修饰符,不经过setter函数.
     */
    public static <T> void setFieldValueDirectly(final T object, final String fieldName, final Object value) {
        Field field = getDeclaredField(object, fieldName);
        setFieldValueDirectly(object,field,value);
    }

    /**
     * 设置对象属性值
     * 先尝试使用经过setter函数，失败的话再直接设置对象属性值,无视private/protected修饰符.
     */
    public static <T> void setFieldValue(final T object, final String fieldName, final Object value) {
        if(object == null){
            return;
        }

        Field field = getDeclaredField(object, fieldName);
        setFieldValue(object, field, value);
    }
    /**
     * 设置对象属性值
     * 先尝试使用经过setter函数，失败的话再直接设置对象属性值,无视private/protected修饰符.
     */
    public static <T> void setFieldValue(final T object, final Field field, final Object value) {
        if(object==null || field == null) {
            return;
        }
        String fieldName = field.getName();
        String methodName="set"+Character.toUpperCase(fieldName.charAt(0))+fieldName.substring(1);
        try {
            Method method = object.getClass().getMethod(methodName, value.getClass());
            method.invoke(object, value);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            try{
                setFieldValueDirectly(object,field,value);
            }catch(Exception e){
                log.error("不可能抛出的异常", e);
            }
        }
    }


    /**
     * 直接读取对象属性值,无视private/protected修饰符,不经过getter函数.
     */
    public static Object getFieldValueDirectly(final Object object, final Field field) {
        makeAccessible(field);

        Object result = null;
        try {
            result = field.get(object);
        } catch (IllegalAccessException e) {
            log.error("不可能抛出的异常", e);
        }
        return result;
    }

    /**
     * 直接读取对象属性值,无视private/protected修饰符,不经过getter函数.
     */
    public static Object getFieldValueDirectly(final Object object, final String fieldName) {
        try{
            Field field = getDeclaredField(object, fieldName);

            if (field == null) {
                throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
            }
            return getFieldValueDirectly(object,field);
        }catch(Exception e){
            log.error("不可能抛出的异常", e);
        }
        return null;
    }
    /**
     * 优先使用Getter方法读取字段值，如果失败再直接读取(无视private/protected修饰符)
     */
    public static Object getFieldValue(final Object object, final String fieldName) {
        if(object == null || fieldName==null){
            return null;
        }
        Field field = getDeclaredField(object, fieldName);
        return getFieldValue(object, field);
    }

    /**
     * 优先使用Getter方法读取字段值，如果失败再直接读取(无视private/protected修饰符)
     */
    public static Object getFieldValue(final Object object, final Field field) {
        if(object==null || field==null){
            return null;
        }
        String fieldName = field.getName();
        try{
            Object value = null;
            String cFieldName = StrUtil.upperFirst(fieldName);//首字母大写
            String methodName = "get"+cFieldName;
            Method getter =  ReflectionUtils.getDeclaredMethod(object, methodName);
            if(getter == null){//boolean型
                methodName = "is"+cFieldName;
                getter = ReflectionUtils.getDeclaredMethod(object, methodName);
            }
            if(getter != null){//调用Getter方法
                try{
                    value = getter.invoke(object);
                    return value;
                } catch(Exception e){
                    log.error("不可能抛出的异常", e);
                }
            }

            //Getter方法获取字段的值失败，再尝试直接读取
            return ReflectionUtils.getFieldValueDirectly(object, field);
        } catch(Exception e){
            log.error("不可能抛出的异常", e);
            return null;
        }
    }















    /**
     * 从枚举值的名称，反向解析枚举值
     * @param enumType - 枚举类型
     * @param name - 枚举值名称
     * @return 没有相关的值，则返回null，否则返回具体的枚举值
     */
    public static <T extends Enum<T>> T getEnumFromName(Class<T> enumType, String name) {
    	return getEnumFromName(enumType, name, null);
    }
    /**
     * 从枚举值的名称，反向解析枚举值
     * @param enumType - 枚举类型
     * @param name - 枚举值名称
     * @param defaultEnum - 默认的枚举值
     * @return 没有相关的值，则返回defaultEnum，否则返回具体的枚举值
     */
    public static <T extends Enum<T>> T getEnumFromName(Class<T> enumType, String name, T defaultEnum) {
		if(enumType == null || name == null){
			return defaultEnum;
		}
		try{
			return Enum.valueOf(enumType, name);
		}catch(Exception e){
			return defaultEnum;
		}
	}
}
